package encodeDecode;

import java.io.IOException;
import java.util.List;
import java.util.Map;

import com.alibaba.fastjson.JSON;

import io.netty.buffer.ByteBuf;
import io.netty.buffer.Unpooled;
import io.netty.channel.ChannelHandlerContext;
import io.netty.handler.codec.MessageToByteEncoder;
import io.netty.handler.codec.MessageToMessageEncoder;
import protocol.IOMessage;

public class IOMessageEncoder extends MessageToByteEncoder<IOMessage>{

	
	public IOMessageEncoder() throws IOException{
		// TODO Auto-generated constructor stub
	}
	
	@Override
	protected void encode(ChannelHandlerContext ctx, IOMessage msg, ByteBuf sendBuf) throws Exception {
		// TODO Auto-generated method stub
		
		System.out.println("encode the message --> " + msg);
		
		if(msg == null || msg.getHeader() == null){
			throw new Exception("The encode message is null");
		}
		
		String sendMes = JSON.toJSONString(msg);
		System.out.println("length ---> " + sendMes.length() + " sendMes ---> " +sendMes);
		
		int length = 0;
		sendBuf.writeInt(length);
		sendBuf.writeBytes(sendMes.getBytes());
		sendBuf.setInt(0, sendBuf.readableBytes() - 4);
		
		System.out.println("encode complete-- index -- " + sendBuf.writerIndex() + " -- > " + sendBuf.toString());
	}
}
